#!/usr/bin/env python
# coding: utf-8
# $Id: ex3producer.py 16 2009-09-09 15:37:32Z fiorix@gmail.com $
# delayed square calculator, producer

import parallels
from twisted.internet import defer, threads, reactor
from ex3consumer import __file__ as consumer

def response(item, n):
    print ' -> square of %d is %d' % (n, item)

def finish(null, pool):
    pool.shutdown()
    reactor.stop()
    print 'bye bye...'

def main():
    # Ah, the powerful Pool class!
    # Here we create a process pool, running 5 parallel
    # consumers.
    #
    # When you put() something to the pool, it will be
    # consumed as soon as possible. If there are no consumers
    # available, itens will be enqueued for further processing.
    #
    # The internal queue size has no limit. The size parameter
    # determines the number of child consumer processes.
    pool = parallels.Pool(consumer, size=5)

    results = []
    for n in range(100, 120):
	# The put() method will always return a Deferred().
	# If, for any reason, you don't want to get back
	# the data processed by the consumer, just ignore it.
	deferred = pool.put(n)
	deferred.addCallback(response, n)
	results.append(deferred)

    fin = defer.DeferredList(results)
    fin.addCallback(finish, pool)

if __name__ == '__main__':
    reactor.callWhenRunning(main)
    reactor.run()
